import { deleteInstructRecord, pageRecord } from '@/services/api/api-instruct-record';
import { parse } from '@/utils/historyUtils';
import { FileImageOutlined, PaperClipOutlined, ReloadOutlined } from '@ant-design/icons';
import { ModalForm, PageContainer } from '@ant-design/pro-components';
import { ProFormInstance } from '@ant-design/pro-form';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, message, Space, Tag, Typography } from 'antd';
import Search from 'antd/es/input/Search';
import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import TreeAddress from '../address/TreeAddress';
import ReceiptAssign from '../receipt/ReceiptAssign';
import AddRecord from '../record/AddRecord';
import DetailsRecord from '../record/DetailsRecord';
import RecordSetting from '../record/RecordSetting';

interface TableInstructProps {
  brainType?: string;
}

const TableInstruct: React.FC<TableInstructProps> = ({ brainType }) => {
  const access = useAccess();

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();

  const [combineId, setCombineId] = useState();

  const [instructId, setInstructIdState] = useState('');

  const [search, setSearch] = useState({
    name: '',
  });

  const columns: ProColumns<InstructRecordData.PageVo>[] = [
    {
      title: '阅读情况',
      dataIndex: 'isView',
      key: 'isView',
      hideInSearch: access.宣传指令x配置x管理员,
      hideInTable: access.宣传指令x配置x管理员,
      valueType: 'select',
      align: 'center',
      width: '80px',
      valueEnum: {
        0: { text: '未阅读' },
        1: { text: '已阅读' },
      },
      render: (_, record) => (
        <Space>
          <Tag color={record.isView === 0 ? '#F9CF59' : '#1AA15F'} key="recordExamineType">
            {record.isView === 0 ? '未阅读' : '已阅读'}
          </Tag>
        </Space>
      ),
    },
    {
      title: '标题',
      dataIndex: 'name',
      key: 'name',
      width: '300px',
      align: 'center',
      ellipsis: true,
      render: (dom, record, _index, action) => {
        return (
          <div
            style={{
              textAlign: 'left',
            }}
          >
            {access.宣传指令x配置x管理员 && (
              <Tag
                color={record.examine === 0 ? '#2db7f5' : record.examine === 2 ? '#f50' : '#87D068'}
              >
                {record.examine === 0 ? '待审批' : record.examine === 2 ? '退回' : '通过'}
              </Tag>
            )}
            <Tag color={record.grade === 1 ? '#f50' : record.grade === 2 ? '#ffd591' : '#2db7f5'}>
              {record.grade === 1 ? '重大' : record.grade === 2 ? '重要' : '一般'}
            </Tag>
            <Tag color={record.type === 1 ? '#f50' : '#ffd591'}>
              {record.type === 1 ? '中宣' : '市宣'}
            </Tag>
            {/* {access.宣传指令x配置x管理员 ? getAssignTypeTag(record.assignType) : <></>} */}
            {access.宣传指令x配置x管理员 && record.isHasView === 1 && record.isView === 0 ? (
              <Tag color={'#F9CF59'} key="tag_is_has_view">
                需要阅读
              </Tag>
            ) : (
              <></>
            )}
            {record.isImage === 1 ? <FileImageOutlined /> : <></>}
            {record.isFile === 1 ? <PaperClipOutlined /> : <></>}
            <DetailsRecord
              item={record}
              onClose={() => {
                action?.reload();
              }}
              instructId={instructId}
            />
          </div>
        );
      },
    },
    {
      title: '发布单位',
      dataIndex: 'createdOrganizationAvatar',
      key: 'createdOrganizationAvatar',
      valueType: 'avatar',
      width: '100px',
      align: 'center',
      search: false,
      render: (dom, record) => {
        return (
          <Typography.Text ellipsis={true} type="secondary">
            <span>{dom}</span>
            {record.createdOrganizationName}
          </Typography.Text>
        );
      },
    },
    {
      title: '发布人',
      dataIndex: 'createdAccountName',
      key: 'createdAccountName',
      hideInSearch: true,
      width: '80px',
      align: 'center',
    },
    {
      title: '回执情况',
      hideInSearch: access.宣传指令x配置x接收者,
      hideInTable: access.宣传指令x配置x接收者,
      dataIndex: 'receipt',
      key: 'receipt',
      valueType: 'avatar',
      width: '80px',
      align: 'center',
      search: false,
      render: (dom, record) => {
        return (
          record.completeType === 3 && (
            <ReceiptAssign
              id={record.id}
              deadlineTime={record.deadlineTime}
              receipt={record.receipt}
              type={'receipt'}
              isRun={record.run === 1}
            />
          )
        );
      },
    },
    {
      title: '阅读情况',
      dataIndex: 'read',
      key: 'read',
      align: 'center',
      hideInTable: access.宣传指令x配置x接收者,
      width: '80px',
      render: (dom, record) => {
        return (
          <ReceiptAssign
            id={record.id}
            deadlineTime={record.deadlineTime}
            receipt={record.read}
            type={'read'}
            isRun={record.run === 1}
          />
        );
      },
    },
    {
      title: '完成情况',
      dataIndex: 'isComplete',
      key: 'isComplete',
      align: 'center',
      valueType: 'select',
      hideInTable: access.宣传指令x配置x管理员,
      width: '300px',
      valueEnum: {
        1: { text: '已完成' },
        0: { text: '未完成' },
      },
      render: (_, record) => {
        let dom;

        if (record.isComplete === 1) {
          //已完成
          if (record.isView === 0) {
            dom = (
              <>
                <Tag
                  color={
                    record?.completeType === 1
                      ? 'error'
                      : record?.completeType === 2
                      ? 'error'
                      : 'error'
                  }
                >
                  {record?.completeType === 1
                    ? '需要阅读'
                    : record?.completeType === 2
                    ? '需要阅读'
                    : '需要回执'}
                </Tag>
              </>
            );
          } else {
            dom = (
              <>
                <Tag color={record?.completeType === 1 ? 'success' : 'success'}>已完成</Tag>
                <Tag color={record?.isCompleteWithinDeadlineTimeOwn === 1 ? 'success' : 'error'}>
                  {record?.isCompleteWithinDeadlineTimeOwn === 1
                    ? '截止时间自己已完成'
                    : '截止时间自己未完成'}
                </Tag>
                <Tag
                  color={
                    record?.isCompleteWithinDeadlineTimeOrganization === 1 ? 'success' : 'error'
                  }
                >
                  {record?.isCompleteWithinDeadlineTimeOrganization === 1
                    ? '截止时间单位已完成'
                    : '截止时间单位未完成'}
                </Tag>
              </>
            );
          }
        } else {
          //未完成
          if (record.isView === 0) {
            //未阅读
            dom = (
              <>
                <Tag
                  color={
                    record?.completeType === 1
                      ? 'error'
                      : record?.completeType === 2
                      ? 'error'
                      : 'error'
                  }
                >
                  {record?.completeType === 1
                    ? '需要阅读'
                    : record?.completeType === 2
                    ? '需要阅读'
                    : '需要回执'}
                </Tag>
              </>
            );
          } else {
            //已阅读
            dom = (
              <>
                <Tag
                  color={
                    record?.completeType === 1
                      ? 'error'
                      : record?.completeType === 2
                      ? 'error'
                      : 'error'
                  }
                >
                  {record?.completeType === 1
                    ? '需要阅读'
                    : record?.completeType === 2
                    ? '需要阅读'
                    : '需要回执'}
                </Tag>
              </>
            );
          }
        }

        return dom;
      },
    },
    {
      title: '指令要求',
      dataIndex: 'completeType',
      key: 'completeType',
      valueType: 'select',
      align: 'center',
      width: '80px',
      hideInTable: !access.宣传指令x配置x管理员,
      valueEnum: {
        1: { text: '无需回执' },
        // 2: { text: '需要阅读' },
        3: { text: '需要回执' },
      },
      render: (_, record) => (
        <Space>
          <Tag color={record?.completeType === 1 ? 'success' : 'error'}>
            {record?.completeType === 1 ? '无需回执' : '需要回执'}
          </Tag>
        </Space>
      ),
    },
    {
      title: '焚毁',
      dataIndex: 'isDisappear',
      key: 'isDisappear',
      valueType: 'select',
      align: 'center',
      width: '80px',
      hideInTable: !access.宣传指令x配置x管理员,
      render: (_, record) => (
        <Space>
          <Tag
            color={
              record?.isDisappear === 1
                ? record?.isAlreadyDestroyed === 1
                  ? 'red'
                  : 'orange'
                : 'green'
            }
          >
            {record?.isDisappear === 1
              ? record?.isAlreadyDestroyed === 1
                ? '已焚毁'
                : '进行中'
              : '不需要'}
          </Tag>
        </Space>
      ),
    },
    {
      title: '                                                     ',
      dataIndex: 'deadlineTime',
      key: 'deadlineTime',
      width: '120px',
      align: 'center',
      search: false,
      render: (_, record) => (
        <span
          style={{
            color: record.run == 1 ? 'green' : 'red',
          }}
        >
          {record.deadlineTime}
        </span>
      ),
    },
    {
      title: '发布日期',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: '120px',
      align: 'center',
      search: false,
    },
    {
      title: '操作',
      valueType: 'option',
      hideInTable: !access.宣传指令x配置x管理员,
      width: '50px',
      fixed: 'right',
      render: (_, row, index, action) => [
        // <EditRecord
        //   key="edit_role"
        //   recored={row}
        //   onRefurbish={() => {
        //     actionRef.current?.reload();
        //   }}
        // />,
        <ModalForm
          key={'modal_form_release_state_release'}
          title={<>是否删除指令 : {row.name}</>}
          content={'删除并销毁内容'}
          trigger={<a>删除</a>}
          autoFocusFirstInput
          modalProps={{
            width: 400,
            // bodyStyle: { textAlign: 'center' },
            destroyOnClose: true,
            onCancel: () => console.log('run'),
          }}
          submitTimeout={2000}
          submitter={{
            submitButtonProps: {
              type: 'primary',
              style: { background: '#FF5500' },
            },
          }}
          onFinish={async (values) => {
            const res = await deleteInstructRecord({ id: row.id });
            if (res.code === 0) {
              message.success('删除成功');
              actionRef.current?.reload();
            }
            return true;
          }}
        />,
      ],
    },
  ];

  useEffect(() => {
    actionRef.current?.reloadAndRest();
  }, [brainType]);

  useEffect(() => {
    const { instructId } = parse(location.search) as { instructId: string };
    setInstructIdState(instructId);
  }, []);

  /**
   * 请求网络
   * @param value
   */
  const request = async (params = {}) => {
    if (brainType) {
      params.brainType = brainType;
    }

    const response = await pageRecord({ ...params, ...search });
    return Promise.resolve({
      data: response.data.data,
      total: response.data.total,
      success: response.code === 0,
    });
  };
  // useEffect(() => {
  //   loadAddressTreeData()
  // }, []);

  // const loadAddressTreeData = async () => {
  //   try {
  //     const response = await treeInstructAddress();
  //     if (response.code === 0) {
  //       setCombineId(response.data[0]?.id)
  //     }
  //   } catch (error) { }
  // };
  return (
    <PageContainer
      header={{
        title: (
          <Space align="center">
            <span>宣传指令</span>
            <Search
              placeholder="搜索"
              onSearch={(value) => {
                console.log('======', value);

                setSearch({
                  ...search,
                  name: value,
                });
                actionRef.current?.reloadAndRest();
              }}
              enterButton
            />
          </Space>
        ),
        style: {
          paddingBlockEnd: 0,
        },
      }}
      extra={
        // access.宣传指令x配置x管理员
        access.宣传指令x配置x管理员 || access.宣传指令x配置x通讯录修改专员
          ? [
              access.宣传指令x联络人 || access.宣传指令x配置x通讯录修改专员 ? (
                <>
                  {access.unIframShowAdmin ? (
                    <RecordSetting onRefurbish={() => actionRef.current?.reload()} />
                  ) : (
                    <></>
                  )}
                  <Button type="primary" onClick={() => actionRef.current?.reload()}>
                    <ReloadOutlined />
                    刷新
                  </Button>
                  <TreeAddress
                    key={'tree_address'}
                    onSave={() => {
                      actionRef.current?.reload();
                    }}
                  />
                  {/* {(combineId !== null && access.宣传指令x配置x通讯录修改专员) && <EditAddress
                  id={combineId}
                  name={'联络人'}
                  onSave={() => {
                    loadAddressTreeData();
                  }}
                />} */}
                </>
              ) : (
                <></>
              ),
              access.宣传指令x发布指令x页面 ? (
                <AddRecord
                  key={'save_record'}
                  onSave={() => {
                    actionRef.current?.reload();
                  }}
                />
              ) : (
                <></>
              ),
            ]
          : [
              <Button type="primary" onClick={() => actionRef.current?.reload()}>
                <ReloadOutlined />
                刷新
              </Button>,
            ]
      }
    >
      <ProTable<InstructRecordData.PageVo>
        style={{
          marginTop: 10,
        }}
        headerTitle={<span>宣传指令</span>}
        ghost
        columns={columns}
        request={request}
        actionRef={actionRef}
        rowKey="id"
        dateFormatter="string"
        bordered
        search={false}
        sticky
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
        toolbar={{}}
        toolBarRender={false}
      />
    </PageContainer>
  );
};

export default TableInstruct;
